'''
1、pd读取数据
2、选择有影响的特征
3、填补缺失值age
4、数据分割
5、转换成字典，对数据集特征抽取将有类别的特征（票类，性别）变成One-Hot编码形式
x_train.to_dict(orient='records')
6、随机森林估计器流程
class sklearn.ensemble.RandomForestClassifier(n_estimators=10, criterion=’gini’,
 max_depth=None, bootstrap=True, random_state=None)
随机森林分类器
n_estimators：integer，optional（default = 10） 森林里的树木数量
criteria：string，可选（default =“gini”）分割特征的测量方法
max_depth：integer或None，可选（默认=无）树的最大深度
bootstrap：boolean，optional（default = True）是否在构建树时使用放回抽样

'''
import matplotlib as plt
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier, export_graphviz

# 1、pd读取数据
data= pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt")

# 2选择有影响的特征
x = data[['pclass','age','sex']]
y = data[['survived']]

# 3填充缺失值
x['age'].fillna(x['age'].mean(),inplace=True)

# 4数据分割
x_train,x_test ,y_train,y_test =train_test_split(x,y)


# 5转换为字典
x_train = x_train.to_dict(orient="records")
x_test = x_test.to_dict(orient="records")
dv = DictVectorizer()

# 特征名
x_train  =dv.fit_transform(x_train)
x_test = dv.transform(x_test)

# print(dv.get_feature_names())
# print(x_train.toarray())

#6 随机森林估计器流程
rfc = RandomForestClassifier(n_estimators=5, max_depth=4, criterion="entropy")
rfc.fit(x_train,y_train)
score = rfc.score(x_test,y_test)
print(score)

# 评估精确率和召回率
y_predict = rfc.predict(x_test)
report = classification_report(y_true=y_test, y_pred=y_predict)
print(report)

